/**
 * Created by Xiaobing on 2016/9/6.
 */
function HotCell() {
    var cell_layer = gis_core.addGraphicsLayer("HotCell_cell_layer", "小区图层");
    var marker_layer = gis_core.addGraphicsLayer("HotCell_marker_layer", "标记图层");
    var isFirst = true;
    var time = null;
    var min = "";
    var max = "";
    var selectid = "";
    var legends = null;
    var cellLayer_click_handle = null;
    //事件注册方法
    //地图改变事件
    var extentchange = function (delta) {
        loadHotCell();
    };
    //加载图例
    var loadLengend = function () {
        $.ajax({
            url: "/gethotcelllegend?time=" + Math.random(),
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    legends = data;
                    initLegend();
                });
                loadHotCell();
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    //创建图例
    var initLegend = function () {
        if (legends == null || legends == undefined || legends.legendItems == "" || legends.legendItems.length == 0) {
            return;
        }
        var content = "";
        for (var i = 0; i < legends.legendItems.length; i++) {
            var legend = legends.legendItems[i];
            var sRgb = "RGB(" + legend.r + ", " + legend.g + ", " + legend.b + ")";
            content += "<div class=\"legend-box\" style=\"background:rgba(" + legend.r + ", " + legend.g + ", " + legend.b + "," + legend.a + ");color:#fff;\"> " + legend.displayName + ":" + legend.valueMin + "-" + legend.valueMax + "</div>";
        }
        var div = $(content);
        gis_layout.createLegend("HotCell_legend", legends.name + "图例", div);
    };
    //查询热度小区
    var loadHotCell = function () {
        if (gis_common.stringIsNullOrWhiteSpace(time)) {
            return;
        }
        cell_layer.clear();
        marker_layer.clear();
        $.ajax({
            url: "/gethotcellsbtses",
            data: {
                time: time,
                max: max,
                min: min,
                extent: JSON.stringify(gis_common.getMapExtent()),
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    createCellCover(data);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createCellCover = function (btses) {
        var xmax = 0.0, ymax = 0.0, xmin = 0.0, ymin = 0.0;

        for (var i = 0; i < btses.length; i++) {
            var bts = btses[i];

            if (xmax == 0.0) {
                xmax = bts.longitude;
                xmin = bts.longitude;
                ymax = bts.latitude;
                ymin = bts.latitude;
            }
            else {
                xmax = bts.longitude > xmax ? bts.longitude : xmax;
                xmin = bts.longitude < xmin ? bts.longitude : xmin;
                ymax = bts.latitude > ymax ? bts.latitude : ymax;
                ymin = bts.latitude < ymin ? bts.latitude : ymin;
            }

            if (bts.tag == "cluster") {
                var point = new esri.geometry.Point(bts.longitude, bts.latitude, gis_core.map.spatialReference);

                var symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 48, 48);
                var graphic = new esri.Graphic(point, symbol);
                cell_layer.add(graphic);

                var text = bts.value + "";
                if (bts.value >= 1000) {
                    text = (bts.value / 1000).toFixed(2) + "万"
                }
                var textSymbol = new esri.symbol.TextSymbol(text);
                textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
                textSymbol.setColor(new esri.Color([255, 255, 255, 1]));
                textSymbol.setOffset(0, -5);
                var textgraphic = new esri.Graphic(point, textSymbol);
                cell_layer.add(textgraphic);
            }
            else {
                var antbw = 30;
                var azimuth = 0;
                var off_azimuth = 0;
                if (bts.cells.length > 1) {
                    antbw = 180.0 / bts.cells.length;
                    off_azimuth = 360.0 / bts.cells.length;
                }
                if (antbw > 30) {
                    antbw = 30;
                }

                for (var j = 0; j < bts.cells.length; j++) {
                    var cell = bts.cells[j];
                    cell.radius = 200;
                    cell.antbw = antbw;
                    if (cell.azimuth == 0) {
                        cell.azimuth = azimuth;
                    }
                    var g = gis_common.createCellGraphic(cell);
                    var symbol = createSymbol(cell.value);
                    g.setSymbol(symbol);
                    cell_layer.add(g);
                    azimuth = azimuth + off_azimuth;

                    if (!gis_common.stringIsNullOrWhiteSpace(selectid) && selectid == cell.id) {
                        marker_layer.clear();
                        var rings = gis_common.createCellCoverRing(cell.longitude, cell.latitude, cell.radius, cell.azimuth, cell.antbw);
                        var p = rings[rings.length / 2];
                        var x = cell.longitude - (cell.longitude - p[0]) / 2;
                        var y = cell.latitude - (cell.latitude - p[1]) / 2;

                        marker_layer.clear();
                        var point = new esri.geometry.Point(x, y, gis_core.map.spatialReference);
                        var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
                        var graphic = new esri.Graphic(point, symbol);
                        marker_layer.add(graphic);
                    }
                }
            }
        }
        if (xmax > 0.0 && isFirst == true) {
            //gis_common.setExtent(xmax + 0.005, ymax + 0.005, xmin - 0.005, ymin - 0.005);
            //isFirst = false;
        }
    };
    var createSymbol = function (val) {
        var max = 0.0, min = 0.0;
        var length = legends.legendItems.length;
        var symbol = new esri.symbol.SimpleFillSymbol();
        symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([200, 112, 181, 207]), 1));
        for (var i = 0; i < length; i++) {
            var l = legends.legendItems[i];
            max = parseFloat(l.valueMax);
            min = parseFloat(l.valueMin);
            if (i == 0 && val < l.valueMax) {
                symbol.setColor(new esri.Color([l.r, l.g, l.b, l.a]));
                break;
            }
            if (i == length - 1 && val >= min) {
                symbol.setColor(new esri.Color([l.r, l.g, l.b, l.a]));
                break;
            }
            if (val >= min && val < max) {
                symbol.setColor(new esri.Color([l.r, l.g, l.b, l.a]));
                break;
            }
        }
        return symbol;
    };
    //加载热度小区表格数据
    var loadHotCellTable = function () {
        var content = "<div>";
        content += "<table id='HotCell_Table'></table>";
        content += "<div id='HotCell_Pager'></div>"
        content += "<div>";
        var div = $(content);

        gis_layout.createLeftWidget("HotCell_JQGrid_Div", "热度小区", div);

        div.find("#HotCell_Table").jqGrid({
            url: '/gethotcellswithpage?time=' + time + "&max=" + max + "&min=" + min,
            datatype: "json",
            width: 400,
            height: 250,
            colNames: ['ID', '小区名称', '地市', "常驻次数", '经度', '纬度'],
            colModel: [{
                name: 'id',
                index: 'id',
                width: 50,
                hidden: true
            }, {
                name: 'name',
                index: 'name',
                width: 70
            }, {
                name: 'cityName',
                index: 'cityName',
                width: 40,
                align: "right"
            }, {
                name: 'value',
                index: 'value',
                width: 20
            }, {
                name: 'longitude',
                index: 'longitude',
                width: 30,
                align: "right"
            }, {
                name: 'latitude',
                index: 'latitude',
                width: 30,
                align: "right"
            }
            ],
            rowNum: 10,
            rowList: [10, 20, 30, 50],
            pager: '#HotCell_Pager',
            mtype: "get",
            viewrecords: true,
            caption: "",
            onSelectRow: function (id) {
                var data = div.find("#HotCell_Table").jqGrid('getRowData', id);
                gis_common.setExtent(parseFloat(data.longitude) + 0.005, parseFloat(data.latitude) + 0.005, parseFloat(data.longitude) - 0.005, parseFloat(data.latitude) - 0.005);
                selectid = data.id;
                loadHotCellKpiDetail(data.id);
            }
        });
    };
    //加载热度小区明细
    var loadHotCellKpiDetail = function (cellId) {
        if (gis_common.stringIsNullOrWhiteSpace(cellId) || gis_common.stringIsNullOrWhiteSpace(time)) {
            return;
        }
        $.ajax({
            url: "/gethotcellkpidetail",
            data: {
                time: time,
                cellid: cellId,
                max: max,
                min: min
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    var kpi = eval(data);
                    createHotCellKpiDetailHtml(data);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createHotCellKpiDetailHtml = function (kpi) {
        var div = gis_common.createKeyValueList(kpi);
        gis_layout.createRightWidget("eHotCell_createHotCellKpiDetailHtml", "小区指标明细", div);
    };
    //topN
    var topNquery = function (keywords, callback) {
        if (gis_common.stringIsNullOrWhiteSpace(time)) {
            return;
        }
        $.ajax({
            url: "/gethotcelltopn",
            data: {
                time: time,
                max: max,
                min: min,
                key: keywords,
                topn: 10

            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var resvalues = eval(req);
                callback(resvalues);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            }
        });
    };

    /**
     * 初始化
     */
    this.init = function () {
        gis_core.addPlugin(this);
        //加载库文件
        gis_core.addExtentChange("hotCell_extentchange", extentchange);
        //注册事件
        if (cellLayer_click_handle != null) {
            dojo.disconnect(cellLayer_click_handle);
        }
        cellLayer_click_handle = cell_layer.on("click", function (evt) {
            var cell = evt.graphic.attributes.data;
            loadHotCellKpiDetail(cell.id);
        });

    };
    /**
     * 销毁
     */
    this.destroy = function () {
        //gis_core.removeExtentChange("realrimemonitoring_extentchange");
        gis_layout.removeLeftWidget();
        gis_layout.removeRightWidget();
    };
    /**
     * 模块信息
     * @type {{id: string, name: string}}
     */
    this.title = {
        id: "00_07_00",
        name: "热度小区"
    };
    /**
     * 清理
     */
    this.clear = function (callbacl) {
        gis_layout.removeLeftWidget();
        gis_layout.removeRightWidget();
        //marker_layer.clear();
        //cell_layer.clear();
    };
    /**
     * 查询条件
     */
    this.createQueryHtml = function (callback) {
        var content = "<div class=\"form-group\">";
        content += "	<label class='col-sm-3 control-label'>查询时间:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "			<input id='hotcell_param_time' type='text' class='form-control' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM'});\"/>";
        content += " 	</div > ";
        content += " </div > ";
        content += "<div class='form-group'>";
        content += " 	<div class='col-sm-9 col-sm-offset-3'>";
        content += "		<button id='hotcell_param_btn_load' class='btn btn-primary'>确 定</button>";
        content += "	</div>";
        content += "</div>";

        var div = $(content);
        div.find("#hotcell_param_btn_load").bind("click", function () {
            //时间
            time = div.find("#hotcell_param_time").val().replace(/-/g, '').replace(/ /g, '');
            if (gis_common.stringIsNullOrWhiteSpace(time)) {
                gis_common.showMessage("请选择时间");
                div.find("#topology_param_time").focus();
                return;
            }
            loadLengend();
            loadHotCellTable();
            gis_common.queryRegisterFun("hotcelltopn", topNquery);
        });
        callback(div);
    };
    /**
     * 区间查询
     * @param callback
     */
    this.createToolQueryExHtml = function (callback) {
        //var content = "<div class=\"form-group\">";
        var content = "<div class=\"form-inline\" role=\"form\">";
        content += "<div class=\"form-group\">"
        content += "    <div class=\"input-group\">";
        content += "        <div class=\"input-group-addon\">最小值:</div>";
        content += "        <input id='hotcell_ex_min' class=\"form-control\" style='width: 50px;' type=\"text\">"
        content += "    </div>";
        content += "</div>";
        content += "<div class=\"form-group\" style='margin-left: 10px;'>"
        content += "    <div class=\"input-group\">";
        content += "        <div class=\"input-group-addon\">最大值:</div>";
        content += "        <input id='hotcell_ex_max'  class=\"form-control\" style='width: 50px;' type=\"text\">"
        content += "    </div>";
        content += "</div>";
        content += "<button id='hotcell_param_btn_load' class='btn btn-primary' style='margin-left: 10px;'>确定</button>";
        content += "<button id='hotcell_param_btn_clear' class='btn btn-link' style='margin-left: 5px;'>清理</button>";
        content += "</div > ";

        var div = $(content);

        div.find("#hotcell_param_btn_load").bind("click", function () {
            min = $("#hotcell_ex_min").val();
            max = $("#hotcell_ex_max").val();
            loadHotCellTable();
            loadHotCell();
        });

        div.find("#hotcell_param_btn_clear").bind("click", function () {
            $("#hotcell_ex_min").val("");
            $("#hotcell_ex_max").val("");
            min = "";
            max = "";
            loadHotCellTable();
            loadHotCell();
        });

        callback(div);
    };
}

var hotCell = null;

function initHotCell() {
    if (hotCell == null) {
        hotCell = new HotCell();
        hotCell.init();
    }
}

function HotCell_createQueryParamHtml() {
    initHotCell();
    gis_layout.createMenubarWithFun("HotCell_createQueryParamHtml", obj, "热度小区", hotCell.createQueryHtml);
}

function HotCell_createToolbarQueryParam() {
    initHotCell();
    gis_layout.createToolbarWithFun("HotCell_createToolQueryExHtml", obj, 350, hotCell.createToolQueryExHtml);
}
